package com.amado.easyui2.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.amado.easyui2.constant.GlobalConstants;
import com.amado.easyui2.domain.CoachCarEntity;
import com.amado.easyui2.domain.User;
import com.amado.easyui2.service.CoachService;
import com.amado.easyui2.service.impl.CoachServiceImpl;
import com.amado.easyui2.servlet.UserServlet.Result;
import com.amado.easyui2.util.JsonUtil;
import com.amado.easyui2.vo.Page;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CoachServlet extends HttpServlet {
	private CoachService coachService = new CoachServiceImpl();
	private static ObjectMapper mapper = new ObjectMapper();
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		String method = arg0.getParameter("method");
		if ("add".equals(method)) {
			add(arg0, arg1);
		} else if ("delete".equals(method)) {
			delete(arg0, arg1);
		} else if ("edit".equals(method)) {
			edit(arg0, arg1);
		} else if ("update".equals(method)) {
			update(arg0, arg1);
		} else if ("query".equals(method)) {
			query(arg0, arg1);
		} else if ("login".equals(method)) {
			login(arg0, arg1);
		}

	}

	private void login(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		String learnCardNumber = arg0.getParameter("learnCardNumber");
		String trainingModel = arg0.getParameter("trainingModel");
		CoachCarEntity coachInfo = new CoachCarEntity(learnCardNumber, trainingModel);
		String verifyCode = arg0.getParameter("VerificationCode");
		String sessionVerifyCode = (String) arg0.getSession(true).getAttribute(verifyCode);
		if (sessionVerifyCode != null && sessionVerifyCode.equals(verifyCode)) {
			arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
			return;
		}
		List<CoachCarEntity> list = coachService.getCoach(coachInfo);
		if (list != null) {
			list.forEach(e -> {
				if (e.getLearnCardNumber() != null && !e.getLearnCardNumber().equals("") && e.getTrainingModel() != null
						&& !e.getTrainingModel().equals("")) {
					arg0.getSession().setAttribute(GlobalConstants.SESSION_USER, learnCardNumber);
					try {
						arg1.sendRedirect("index.jsp");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} else {
					arg0.setAttribute("msg", "用户名或密码错误");
					try {
						arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
					} catch (ServletException e1) {
						e1.printStackTrace();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			});
		}
	}

	private void query(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Page page = new Page();
		String strPage = arg0.getParameter("page");
		String strRows = arg0.getParameter("rows");
		int pageOne = strPage == null ? 1 : Integer.parseInt(strPage);
		int rows = strRows == null ? 5 : Integer.parseInt(strRows);
		String tm = arg0.getParameter("tm");
		String lcn = arg0.getParameter("lcn");
		page.setCurrentPage(pageOne);
		page.setRowSize(rows);
		Page<CoachCarEntity> pageList = coachService.listAll(tm, lcn, page);
		PrintWriter out = arg1.getWriter();
		out.print(mapper.writeValueAsString(pageList));

	}

	private void update(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");
		CoachCarEntity coachInfo = JsonUtil.jsonToBean(strJson, CoachCarEntity.class);
		Long id = coachInfo.getID();
		String bhAbbreviate = coachInfo.getBhAbbreviate();
		String deleteLogo = coachInfo.getDeleteLogo();
		String learnCardNumber = coachInfo.getLearnCardNumber();
		String oldLearnCardNumber = coachInfo.getOldLearnCardNumber();
		String carColoc = coachInfo.getCarColoc();
		String carrriageNumber = coachInfo.getCarrriageNumber();
		String engineNumber = coachInfo.getEngineNumber();
		String trainingModel = coachInfo.getTrainingModel();
		String paraphraseWay = coachInfo.getParaphraseWay();
		String indexNumberNumber = coachInfo.getIndexNumberNumber();
		String bodyColorCar = coachInfo.getBodyColorCar();
		String automobileBrand = coachInfo.getAutomobileBrand();
		String carType = coachInfo.getCarType();
		Date registerDay = coachInfo.getRegisterDay();
		Date comeintoserviceDay = coachInfo.getComeintoserviceDay();
		Date yearCarefulTime = coachInfo.getYearCarefulTime();
		String yearCarefulState = coachInfo.getYearCarefulState();
		Date createTime=coachInfo.getCreateTime();
		Date updateTime=coachInfo.getUpdateTime();
		String createName=coachInfo.getCreateName();
		String updateName=coachInfo.getUpdateName();
		CoachCarEntity coach = new CoachCarEntity(id, bhAbbreviate, deleteLogo, learnCardNumber, oldLearnCardNumber,
				carColoc, carrriageNumber, engineNumber, trainingModel, paraphraseWay, indexNumberNumber, bodyColorCar,
				automobileBrand, carType, registerDay, comeintoserviceDay, yearCarefulTime, yearCarefulState,createTime,updateTime,createName,updateName);
		coachService.update(coach);
	}

	private void edit(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
		Long id = Long.valueOf(arg0.getParameter("id"));
		List<CoachCarEntity> list = coachService.list();
		for (CoachCarEntity coach : list) {
			if (coach.getID().equals(id)) {
				CoachCarEntity coachId = coach;
				PrintWriter out = arg1.getWriter();
				out.print(mapper.writeValueAsString(coachId));
				break;
			}
		}

	}
//	Long id = Long.valueOf(arg0.getParameter("id"));
//	List<User> list = userService.list();
//	for (User user : list) {
//		if (user.getId().equals(id)) {
//			User userId = user;
//			PrintWriter out = arg1.getWriter();
//			out.print(mapper.writeValueAsString(userId));
//			break;

	private void delete(HttpServletRequest arg0, HttpServletResponse arg1) throws IOException {
//		String delete = arg0.getParameter("delete");
//		if (delete != null && delete.trim() != "") {
//			coachService.delete(Long.valueOf(delete));
//			arg1.getWriter().print(JsonUtil.beanToJson(new Result()));
//		} else {
//			arg1.getWriter().print(JsonUtil.beanToJson(new Result("0", "参数错误")));
//		}
		PrintWriter out = arg1.getWriter();
		try {

			String ids = arg0.getParameter("ids");
			if (ids != null) {
				String[] idArray = ids.split(",");
				if (idArray.length > 5) {
					out.println(mapper.writeValueAsString(new Result("2", "删除的数不能超过5个")));
				} else {
					List<Long> idList = new ArrayList<>();
					for (String tempId : idArray) {
						idList.add(Long.valueOf(tempId));
					}
					coachService.delete(idList);
					out.print(mapper.writeValueAsString(new Result()));
				}
			}
		} catch (Exception e) {
			out.print(mapper.writeValueAsString(new Result("2", e.getMessage())));
		}

	}

	class Result {
		// 0失败，1成功
		private String resultCode = "1";
		private String resultMessage = "成功";

		public Result() {
		}

		public Result(String resultCode, String resultMessage) {
			super();
			this.resultCode = resultCode;
			this.resultMessage = resultMessage;
		}

		public String getResultCode() {
			return resultCode;
		}

		public void setResultCode(String resultCode) {
			this.resultCode = resultCode;
		}

		public String getResultMessage() {
			return resultMessage;
		}

		public void setResultMessage(String resultMessage) {
			this.resultMessage = resultMessage;
		}
	}

	private void add(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");
		CoachCarEntity coachEntityInfo = JsonUtil.jsonToBean(strJson, CoachCarEntity.class);
		coachService.add(coachEntityInfo);

	}
}